package com.aifund.app.interceptor;

import com.aifund.common.entity.TokenEntity;
import com.aifund.common.enums.CommonEnum;
import com.aifund.common.enums.redis.RedisSetKey;
import com.aifund.common.result.ResultBody;
import com.aifund.common.service.SystemConfigService;
import com.aifund.common.util.RedisUtil;
import com.alibaba.fastjson.JSON;
import com.google.common.base.Utf8;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @Description:拦截器
 * @author: Yangxf
 * @date: 2019/4/14 12:58
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Autowired
    protected RedisUtil redisUtil;
    @Autowired
    protected SystemConfigService systemConfigService;
    //提供查询
    @Override
    public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
            throws Exception {}
    @Override
    public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
            throws Exception {}
    @Override
    public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
        //此处为不需要登录的接口放行
        if (arg0.getRequestURI().contains("/api/login/**") || arg0.getRequestURI().contains("/api/register/**") || arg0.getRequestURI().contains("/error") || arg0.getRequestURI().contains("/static")) {
            return true;
        }
        //权限路径拦截
        //PrintWriter resultWriter = arg1.getOutputStream();
        // TODO: 有时候用PrintWriter 回报 getWriter() has already been called for this response
        arg1.setCharacterEncoding("UTF-8");
        arg1.setContentType("application/json;;charset=UTF-8");
        ServletOutputStream resultWriter = arg1.getOutputStream();
        final String headerToken=arg0.getHeader("token");
        //判断请求信息
        if(null==headerToken||"".equals(headerToken.trim())){
            ResultBody resultBody = ResultBody.error(CommonEnum.SIGNATURE_NOT_MATCH.getResultCode(),"我没有你的token？,需要登录");
            resultWriter.write(JSON.toJSONString(resultBody).getBytes("UTF-8"));
            resultWriter.flush();
            resultWriter.close();
            return false;
        }
        //解析Token信息
        try {
            Claims claims = Jwts.parser().setSigningKey(systemConfigService.getJwtSecret()).parseClaimsJws(headerToken).getBody();
            String tokenUserId=(String)claims.get("userId");
            long iTokenUserId = Long.parseLong(tokenUserId);
            //根据客户Token查找数据库Token
            TokenEntity myToken= (TokenEntity) redisUtil.hget(RedisSetKey.USER_TOKEN.getSetKey(),iTokenUserId+"");

            //数据库没有Token记录
            if(null==myToken) {
                ResultBody resultBody = ResultBody.error(CommonEnum.SIGNATURE_NOT_MATCH.getResultCode(),"我没有你的token？,需要登录");
                resultWriter.write(JSON.toJSONString(resultBody).getBytes("UTF-8"));
                resultWriter.flush();
                resultWriter.close();
                return false;
            }
            //数据库Token与客户Token比较
            if( !headerToken.equals(myToken.getToken()) ){
                ResultBody resultBody = ResultBody.error(CommonEnum.SIGNATURE_NOT_MATCH.getResultCode(),"你的token修改过？,需要登录");
                resultWriter.write(JSON.toJSONString(resultBody).getBytes("UTF-8"));
                resultWriter.flush();
                resultWriter.close();
                return false;
            }
        } catch (Exception e) {
            ResultBody resultBody = ResultBody.error(CommonEnum.SIGNATURE_NOT_MATCH.getResultCode(),"token过期或者token无效,需要登录");
            resultWriter.write(JSON.toJSONString(resultBody).getBytes("UTF-8"));
            resultWriter.flush();
            resultWriter.close();
            return false;
        }
        //最后才放行
        return true;
    }

}
